/*
          prev maxtri

        P
        ↓
        
N →         0	3	1	4	2	5	6
        0	0	0	0	3	3	3	0
        4	0	0	0	3	3	3	0
        2	1	1	1	4	4	4	1
        3	1	1	1	4	4	4	1
        1	2	2	2	5	5	5	2
        5	2	2	2	5	5	5	2
        6	-	-	-	-	-	-	6

        x   a       x   c       y   b       x   b       y   a       y   c       x   b
         \ /         \ /         \ /         \ /         \ /         \ /         \ /
          0           1           2           3           4           5           6
         / \         / \         / \         / \         / \         / \         / \
        a   x       b   x       c   x       a   y       b   y       c   y       b   x

        x   c       x   b
          1    <==>   6
        b   x       b   x
*/
export const PREV_MAP = {
    0: { 0: 0, 3: 0, 1: 0, 4: 3, 2: 3, 5: 3, 6: 0 },
    4: { 0: 0, 3: 0, 1: 0, 4: 3, 2: 3, 5: 3, 6: 0 },
    2: { 0: 1, 3: 1, 1: 1, 4: 4, 2: 4, 5: 4, 6: 1 },
    3: { 0: 1, 3: 1, 1: 1, 4: 4, 2: 4, 5: 4, 6: 1 },
    1: { 0: 2, 3: 2, 1: 2, 4: 5, 2: 5, 5: 5, 6: 2 },
    5: { 0: 2, 3: 2, 1: 2, 4: 5, 2: 5, 5: 5, 6: 2 },
    6: { 0:-1, 3: -1, 1: -1, 4: -1, 2: -1, 5: -1, 6: 6 },
};

/**
 * 
 * @param {Number} p prev
 * @param {Number} n next
 * @returns prev num before convertion
 */
export const pv = (p, n) => PREV_MAP[p]?.[n] ?? -1;

export const prev = (num) => {
    let num1 = [0, ...num, 6];
    let num2 = [];
    for (let i = 0; i < num1.length - 1; i++) {
        num2.push(pv(num1[i], num1[i + 1]))
    }
    
    // const num2 = num1.silce(0,-1).map((n, idx) => pv(n, n[idx + 1]));

    while (num2[0] === 0) {
        num2.shift();
    }
    while (num2[num2.length - 1] === 6) {
        num2.pop();
    }
    return num2;
}

const deduct = (num, i = 1) => {
    let num1 = Array.from(num);
    while (i--) {
        if (num1.length <= 1) break;
        console.log(num1.join(''));
        num1 = prev(num1);
    }
}

const deductStr = (str, i = 1) => deduct(str.split('').map(e => +e), i);



// test unit
const tuint = () => {
    console.log(prev([3, 0, 5]));//"132<-305"
    console.log(prev([1, 3, 2]));//"241<-132"
    console.log(prev([4, 0, 4, 1]));//"4041<-30302"

    console.log(deductStr('321', 5));

};

// tuint();